﻿using Nest;
using System;

namespace Infrastructure.ElasticSearch.ParentChilds
{
    public class HasChildSpecification<TParent, TChild> : ISearchSpecification<ISearchRequest<TParent>>
        where TParent : class
        where TChild : class
    {
        private readonly string _childType;
        private readonly Func<BoolQueryDescriptor<TChild>, IBoolQuery> _selector;

        public HasChildSpecification(string childType,
            Func<BoolQueryDescriptor<TChild>, IBoolQuery> selector)
        {
            _childType = childType;
            _selector = selector;
        }

        public ISearchRequest<TParent> IsSatisfiedBy()
        {
            return new SearchDescriptor<TParent>()
                .Query(q => q
                    .HasChild<TChild>(m => m
                        .Type(_childType)
                        .Query(r => r
                            .Bool(_selector))
                    )
                );
        }
    }
}